#import "CTHomeVC.h"
#import <ContactsUI/ContactsUI.h>
#import "CTInfoVC.h"
#import <AppsFlyerLib/AppsFlyerLib.h>
#import "CTLocationManager.h"
#import "NSDictionary+WBJSONString.h"
@interface CTHomeVC () <CNContactPickerDelegate>
@property (nonatomic ,strong) CNContact *selctContact;
@end
@implementation CTHomeVC
- (void)viewDidLoad {
    [super viewDidLoad];
    [self registerWebHandler];
    [self startRequest];
    [self observeRAC];
}
- (void)goBackAction:(id)sender{
    if ([self.webView canGoBack]) {
        NSDictionary *dic = @{ @"type" : @"onLeftIconClick"};
        [self.bridge callHandler:@"JavascriptHandler" data:[dic mj_JSONString]];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)startRequest {
    [super startRequest];
    NSLog(@"-----Home url: %@", self.url);
}
- (void)observeRAC {
    @weakify(self);
    [self.topBar.var_onlineServiceSubject subscribeNext:^(id x) {
        @strongify(self);
        NSDictionary *dic = @{@"type" : @"onRightIconClick"};
        [self.bridge callHandler:@"JavascriptHandler" data:[dic mj_JSONString]];
    }];
    [self.topBar.var_msgCenterClickSubject subscribeNext:^(id x) {
        @strongify(self);
        NSDictionary *dic = @{@"type" : @"onSubRightIconClick"};
        [self.bridge callHandler:@"JavascriptHandler" data:[dic mj_JSONString]];
    }];
    [self.topBar.var_textBtnClickSubject subscribeNext:^(id x) {
        @strongify(self);
        NSDictionary *dic = @{@"type" : @"onRightIconClick"};
        [self.bridge callHandler:@"JavascriptHandler" data:[dic mj_JSONString]];
    }];
}
#pragma mark - register JS
- (void)registerWebHandler
{
    [self.bridge registerHandler:@"CreditSuccess" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@"CreditSuccess js");
    }];
    CTUserModel *model = [CTUserManager shareManager].userModel;
    if (model != nil) {
        NSDictionary *userDic = [model model_keyValues];        
        NSDictionary *dic = @{@"type":@"refreshUserInfo",
                              @"userInfo":userDic};
        [self.bridge callHandler:@"JavascriptHandler" data:[dic mj_JSONString]];
    }
    NSDictionary *dic = @{@"type":@"transmitChannel",
                          @"channel":[CTAFManager getChannel]};
    [self.bridge callHandler:@"JavascriptHandler" data:[dic mj_JSONString]];
    WeakSelf(weakSelf);
    [self.bridge registerHandler:@"ObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *value = [data ct_valueForKey:@"type"];
        NSLog(@"\n----Type:%@ %@",value, data);
        if ([value isEqualToString:@"enterLogin"]) {
        }
        if ([value isEqualToString:@"relogin"]) {
            NSDictionary *dic = @{@"phone" : [CTUserManager shareManager].userModel.wirelessDeviceNumber, @"exit" : @"1"};
            responseCallback([dic mj_JSONString]);
            [[CTUserManager shareManager] userLogout];
        }
        if ([value isEqualToString:@"h5LoginSuccess"]) {
            CTUserModel *uerModel = [CTUserModel modelWithDictionary:data];
            [[CTUserManager shareManager] updateUserInfo:uerModel];
            NSString *mobile = [data ct_valueForKey:@"wirelessDeviceNumber"];
            [CTUserManager cachePhone:mobile];
            [CTUploadManager ct_uploadType:CTUploadTypeDevice];
            [CTUploadManager ct_uploadType:CTUploadTypeLocation];
            [CTUploadManager ct_uploadType:CTUploadTypeLogin];
            [CTUploadManager ct_uploadType:(CTUploadTypeUpdateRegSubChannel) data:@{}];
        }
        if ([value isEqualToString:@"regSuccess"]) {
            [CTUploadManager ct_uploadType:CTUploadTypeDevice];
            [CTUploadManager ct_uploadType:CTUploadTypeLocation];
            [CTUploadManager ct_uploadType:CTUploadTypeLogin];
            [CTUploadManager ct_uploadType:CTUploadTypeRegister];
        }
        if ([value isEqualToString:@"title"]) {
            weakSelf.topBar.var_titleLabel.text = returnBeNil(data[@"title_txt"]);
            weakSelf.topBar.backgroundColor = [UIColor colorWithHexString:returnBeNil(data[@"title_bg"])];
            self.topBar.var_titleLabel.textColor = [UIColor colorWithHexString:returnBeNil(data[@"title_txtcolor"])];
            if ([[data ct_valueForKey:@"is_main"] isEqualToString:@"1"]) {
                BOOL showOnlineService = [[NSUserDefaults standardUserDefaults] boolForKey:kShowOnlineService];
                if (showOnlineService) {
                    [self showOnlineServiceButton:YES];
                } else {
                    [self showOnlineServiceButton:NO];
                }
            } else {
                [self showOnlineServiceButton:NO];
            }
            if ([[data ct_valueForKey:@"left_icon_type"] isEqualToString:@"icon"]) {
                NSString *leftValue = [data ct_valueForKey:@"left_icon_value"];
                if ([leftValue isEqualToString:@"1"]) {
                    [self showLeftButton:YES];
                } else {
                    [self showLeftButton:NO];
                }
            } else if ([[data ct_valueForKey:@"left_icon_type"] isEqualToString:@"text"]){
                NSString *rightValue = [data ct_valueForKey:@"right_icon_value"];
                [self.topBar.var_msgCenterBtn setTitle:rightValue forState:UIControlStateNormal];
            } else {
                [self showLeftButton:NO];
            }
            if ([[data ct_valueForKey:@"right_icon_type"] isEqualToString:@"icon"]) {
                NSString *leftValue = [data ct_valueForKey:@"right_icon_value"];
                if ([leftValue isEqualToString:@"4"]) {
                    [self showMsgCenterButton:YES];
                } else {
                    [self showMsgCenterButton:NO];
                }
            } else if ([[data ct_valueForKey:@"right_icon_type"] isEqualToString:@"text"]){
                [self showTestButton:YES];
                NSString *rightValue = [data ct_valueForKey:@"right_icon_value"];
                [self.topBar.var_textBtn setTitle:rightValue forState:UIControlStateNormal];
            } else {
                [self hideMsgAndTextButton];
            }
        }
        if ([value isEqualToString:@"getUserInfo"]) {
            CTUserModel *model = [CTUserManager shareManager].userModel;
            NSDictionary *dic = [model model_keyValues];
            responseCallback([dic mj_JSONString]);
            NSLog(@"++++Home: getUserInfo:%@ \n",dic);
        }
        if ([value isEqualToString:@"toExtendCredit"]) {
            CTInfoVC *homeVC = [[CTInfoVC alloc] initWithResult:^(BOOL isSuccess) {                
                NSDictionary *dic = @{@"type":@"CreditSuccess",
                                      @"isCreditSuccess":@(isSuccess)};
                [self.bridge callHandler:@"JavascriptHandler" data:[dic mj_JSONString]];
            }];
            [self.navigationController pushViewController:homeVC animated:YES];
        }
        if ([value isEqualToString:@"getPermissionContact"]) {
            NSDictionary *data = @{@"type": @"getPermissionContact",
                                   @"state" : @"-1"};
            [weakSelf.bridge callHandler:@"JavascriptHandler" data:[data mj_JSONString]];
            NSLog(@"\n++++Home: getPermissionContact");
        }
        if ([value isEqualToString:@"getContacts"] || [value isEqualToString:@"contacts"]) {
            CNContactPickerViewController * pickerVC = [[CNContactPickerViewController alloc]init];
            pickerVC.delegate = weakSelf; 
            [weakSelf presentViewController:pickerVC animated:YES completion:nil];
            NSLog(@"\n++++Home: ");
        }
        if ([value isEqualToString:@"openTempContacts"]) {
            CNContactPickerViewController * pickerVC = [[CNContactPickerViewController alloc]init];
            pickerVC.delegate = weakSelf; 
            [weakSelf presentViewController:pickerVC animated:YES completion:nil];
            NSLog(@"\n++++Home: ");
        }
        if ([value isEqualToString:@"uploadPhoto"]) {
        }
        if ([value isEqualToString:@"encrypt"]) {
            NSString *encryptedData = [data objectForKey:@"beforeEncryptedData"];
            NSDictionary *dic = @{@"type" : @"encrypt",
                                  @"encryptedData" : [CTEncryptTool encryptInfo:encryptedData],
            };
            responseCallback([dic mj_JSONString]);
            NSLog(@"\n++++Home: :%@ \n",dic);
        }
        if ([value isEqualToString:@"checkPhoneNumLogged"]) {
            NSString *phone = [data objectForKey:@"phoneNum"];
            BOOL ex = !beNil(phone) && [CTUserManager checkPhoneHasLogged:phone];
            NSString *exit = ex ? @"1" : @"0";
            NSDictionary *dic = @{@"type":@"checkPhoneNumLogged",@"phone":phone,@"exit":exit};
            responseCallback([dic mj_JSONString]);
            NSLog(@"\n++++Home: :%@ \n", dic);
        }
        if ([value isEqualToString:@"getZuid"]) {
            NSString *zuid = [CTUserManager ct_getZuid];
            NSDictionary *dic = @{@"zuid" : zuid};
            responseCallback([dic mj_JSONString]);
            NSLog(@"\n++++Home: :%@", dic);
        }
        if ([value isEqualToString:@"getChannel"]) {
            NSDictionary *dic = @{@"type" : @"transmitChannel",
                                  @"channel" : [CTAFManager getChannel]
            };
            [self.bridge callHandler:@"JavascriptHandler" data:dic];
            responseCallback([dic mj_JSONString]);
            NSLog(@"\n++++Home: :%@", dic);
        }
        if ([value isEqualToString:@"backEvent"]) {
            [self.webView goBack];
        }
        if ([value isEqualToString:@"openShare"]) {
        }
        if ([value isEqualToString:@"bombTxt"]) {
            NSString *bombTxt = [data ct_valueForKey:@"bombTxt"];
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = bombTxt;
            [self.view showText:@"Successful replication"];
        }
        
        //
        if ([value isEqualToString:@"wakeUpAppByPackageName"]) {
            NSString *appPackage = [data ct_valueForKey:@"iosPackageName"];
            NSString *scheme = [NSString stringWithFormat:@"%@://",appPackage];
            NSURL *url = [NSURL URLWithString:scheme];
            BOOL canOpenURL = [[UIApplication sharedApplication] canOpenURL:url];
            if (canOpenURL) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            } else {
                NSString *iosDownLoadUrl = [data ct_valueForKey:@"iosDownLoadUrl"];
                NSURL *downUrl = [NSURL URLWithString:iosDownLoadUrl];
                [[UIApplication sharedApplication] openURL:downUrl options:@{} completionHandler:nil];
            }
        }
        if ([value isEqualToString:@"scoreApp"]) {
            NSString *appUrl = @"https://apps.apple.com/ng/app/id6578425154?action=write-review";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appUrl] options:@{} completionHandler:nil];
        }
        if ([value isEqualToString:@"analyticsEvent"]) {
            NSString *event = [data ct_valueForKey:@"event"];
            if ([event hasPrefix:@"AF"]){
                [[AppsFlyerLib shared] logEvent:event withValues:@{}];
            }
        }
        if ([value isEqualToString:@"location"]) {
            [CTUploadManager ct_uploadType:CTUploadTypeLocation];
        }
        if ([value isEqualToString:@"DEV01"]) {
            [CTUploadManager ct_uploadType:CTUploadTypeDevice];
        }
        if ([value isEqualToString:@"makecall"]) {
            NSString *phone = [data ct_valueForKey:@"phoneNum"];
            NSMutableString * aStr=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phone];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:aStr] options:@{} completionHandler:nil];
        }
        if ([value isEqualToString:@"judgePermissionLoc"]) {
            switch (CLLocationManager.authorizationStatus) {
                case kCLAuthorizationStatusNotDetermined:
                case kCLAuthorizationStatusDenied: {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [[CTLocationManager sharedManager] showAlert];
                    });
                }
                    break;
                default:
                    break;
            }
        }
    }];
}
#pragma mark - CNContactPickerDelegate
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
}
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    self.selctContact = contact;
    NSArray *phoneNums = contact.phoneNumbers;
    NSMutableArray *contactArray = [NSMutableArray arrayWithCapacity:phoneNums.count];
    for (CNLabeledValue *phone in phoneNums) {
        NSString *name = [NSString stringWithFormat:@"%@%@", contact.familyName, contact.givenName];
        NSString *phoneStr =((CNPhoneNumber *)phone.value).stringValue;
        phoneStr = [phoneStr cleanPhoneNumber];
        NSMutableDictionary *contactInfo = [[NSMutableDictionary alloc] init];
        [contactInfo setObject:@"contacts" forKey:Contact_type];
        [contactInfo setObject:@"1" forKey:Contact_status];
        [contactInfo setObject:name forKey:Contact_name];
        [contactInfo setObject:phoneStr forKey:Contact_mobile];
        [contactArray addObject:contactInfo];
    }
    if (phoneNums.count == 0) {
        NSString *name = [NSString stringWithFormat:@"%@%@", contact.familyName, contact.givenName];
        NSMutableDictionary *contactInfo = [[NSMutableDictionary alloc] init];
        [contactInfo setObject:@"contacts" forKey:Contact_type];
        [contactInfo setObject:name forKey:Contact_name];
        [contactInfo setObject:@"" forKey:Contact_mobile];
        [contactInfo setObject:@"0" forKey:Contact_status];
        [contactArray addObject:contactInfo];
    }
    NSDictionary* uploadDic = [[NSDictionary alloc] initWithObjectsAndKeys:contactArray, @"statistics", @"getContacts", @"type", @"",@"allContacts", nil];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:uploadDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [self.bridge callHandler:@"JavascriptHandler" data:jsonString];
}
@end
